package lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ypz
 * @date 2021/9/28 11:24
 */
public class 互斥锁Demo {
    public Object getData(String key) throws InterruptedException {
        //定义一个互斥锁
        ReentrantLock reentrantLock = new ReentrantLock();
        //从redis中读取数据
        Object result = getDataFromRedis(key);
        if (result == null){
            //去获取锁，获取成功，则去数据库读取数据
            if (reentrantLock.tryLock()){
                result = getDataFromMysql(key);
                //更新缓存数据
                if (result != null){
                    setDataFromRedis(key,result);
                }
                reentrantLock.unlock();
            }
            //获取锁失败,则等待100ms再次去获取锁
            else{
                Thread.sleep(100);
                result = getData(key);
            }
        }
        return result;
    }

    private void setDataFromRedis(String key, Object result) {
    }

    private Object getDataFromMysql(String key) {
        return null;
    }

    private Object getDataFromRedis(String key) {
        return null;
    }
}
